import { setToken, getToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: {}, // 存储用户的信息
  routes: constantRoutes
}

const mutations = {
  //  存储token
  setToken(state, newToken) {
    state.token = newToken
    // 持久化
    setToken(newToken)
  },
  removeToken(state) {
    state.token = ''
    // 清除持久化cookies中的token
    removeToken()
  },
  updateUserInfo(state, info) {
    state.userInfo = info
  },
  setRoutes(state, asyncRoutes) {
    state.routes = [...constantRoutes, ...asyncRoutes]
  }
}

const actions = {
  logout(context) {
    // 清空token和情况用户信息
    context.commit('removeToken')
    context.commit('updateUserInfo', {})
    // 重置路由---》怎么重置路由
    resetRouter()
  },
  async login(context, data) {
    // 发送请求实现登录 ，假设已经完成  token 123456
    const token = await login(data)
    context.commit('setToken', token)
  },
  async getInfo(context) {
    const info = await getUserInfo()
    console.log(info, 'getUserInfo')
    context.commit('updateUserInfo', info)
    return info
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

